<template>
  <div class="base-echart">
    <div class="echarts" ref="echartRef"></div>
  </div>
</template>

<script setup lang="ts">
  import * as echarts from 'echarts'
  import type { EChartsOption } from 'echarts'
  import { onBeforeMount, onMounted, ref, watchEffect } from 'vue'
  import { throttle } from 'lodash'

  interface IProps {
    options: EChartsOption
  }

  const echartRef = ref<HTMLElement>()

  const $props = withDefaults(defineProps<IProps>(), {})
  const echartsInstance = ref<any>()
  onMounted(() => {
    echartsInstance.value = echarts.init(echartRef.value, 'light', { renderer: 'canvas' })
    watchEffect(() => {
      echartsInstance.value && echartsInstance.value.setOption($props.options)
    })

    window.addEventListener(
      'resize',
      throttle(() => {
        echartsInstance.value.resize()
      })
    )
  })

  onBeforeMount(() => {
    window.removeEventListener('resize', () => {
      echartsInstance.value.resize()
    })

    echartsInstance.value && echartsInstance.value.dispose()
  })
</script>

<style lang="scss" scoped></style>
